<?php

class TaskLog{

	/**
	 * 添加
	 *
	 * @param unknown_type $name
	 * @param unknown_type $parent
	 * @param unknown_type $ord
	 */
	function add($data){
		
		$data['created'] = full_date();
		$data['ip'] 	= real_ip();
		
		$m = M('TaskLog');
		//返回自增id
		$id = $m->add($data);
		
		return $id;
	}
	
	/**
	 * 修改
	 *
	 * @param unknown_type $id
	 * @param unknown_type $upItems
	 * @return unknown
	 */
	function update($id,$upItems){
		$m = M('TaskLog');
		return $m -> where('id='.$id)->save($upItems);
	}
	
	/**
	 * 
	 * 任务单列表
	 * @param $id
	 */
	function select_by_task_id($id){
		$m = M('TaskLog');
		$logs = $m ->table('task_log t')
		->join('admin a ON a.id = t.admin_id')
		->join("status_type stp ON stp.status_id = t.pay_status AND stp.type_code= 'task_pay_status'")
		->join("status_type sts ON sts.status_id = t.task_status AND sts.type_code= 'task_status'")
		->where('t.task_id='.$id)
		->field("
			t.*,a.real_name,
			REPLACE(stp.status_style,'#string',stp.status_name) AS pay_status_name,
			REPLACE(sts.status_style,'#string',sts.status_name) AS task_status_name")
		->order('t.id DESC')
		->select();
		
		if(is_array($logs)){
			foreach ($logs as $i => $l){
				$logs[$i]['no'] = $i + 1;
			}
		}
		
		return $logs;
	}
	
	function get_by_task_id($id){
		$m = M('TaskLog');
		return $m -> getByTaskId($id);
	}

    /**
     * 获取最后的任务记录
     * @param $task_ids
     * @return mixed
     */
    function get_last_task_log($task_ids){

        $task_id_str = '0';
        if(!empty($task_ids)){
            $task_id_str = implode(',',$task_ids);
        }

        $m = M('TaskLog');
        $logs = $m ->table('task_log t')
            ->join('admin a ON a.id = t.admin_id')
            ->join("INNER JOIN (SELECT max(id) AS max_id,COUNT(id) AS log_count FROM `task_log` WHERE task_id IN ($task_id_str) GROUP BY task_id) tp_t ON tp_t.max_id = t.id")
            ->join("status_type sts ON sts.status_id = t.task_status AND sts.type_code= 'task_status'")
            ->join("status_type stp ON stp.status_id = t.pay_status AND stp.type_code= 'task_pay_status'")
            ->field("
			t.*,a.real_name,
			tp_t.log_count,
			REPLACE(stp.status_style,'#string',stp.status_name) AS pay_status_name,
			REPLACE(sts.status_style,'#string',sts.status_name) AS task_status_name")
            ->group("t.task_id")
            ->select();

        return $logs;
    }
}